package quiz;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AddQuestionServlet
 */
@WebServlet("/AddQuestion")
public class AddQuestionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddQuestionServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataBase db = (DataBase)request.getServletContext().getAttribute("db");

		int id = Integer.parseInt(request.getParameter("id"));
		request.setAttribute("quiz", db.getQuiz(id));
		
		RequestDispatcher dpatch = request.getRequestDispatcher("add-questions.jsp");
		dpatch.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Account acct = (Account) request.getSession().getAttribute("account");
		if (acct == null){
			request.setAttribute("error", "You're not logged in!  Please sign in to add a question.");
			RequestDispatcher dpatch = request.getRequestDispatcher("login.jsp");
			dpatch.forward(request, response);
			return;
		}
		
		int quizID = Integer.parseInt((String)request.getParameter("quizID"));
		
		int numAnswers;
		try{numAnswers = Integer.parseInt((String)request.getParameter("numberAnswers"));}
		catch (NumberFormatException e) {
			//if the number of answers is incorrectly formatted
			request.setAttribute("error", "You didn't enter a valid number for number of answers.");
			
			DataBase db = (DataBase)request.getServletContext().getAttribute("db");
			request.setAttribute("quiz", db.getQuiz(quizID));
			
			RequestDispatcher dpatch = request.getRequestDispatcher("add-questions.jsp");
			dpatch.forward(request, response);
			return;
		}
		
		//if the number of answers entered is less than 0
		if (numAnswers <= 0){
			request.setAttribute("error", "You need at least one answer to the question.");
			
			DataBase db = (DataBase) request.getServletContext().getAttribute("db");
			request.setAttribute("quiz", db.getQuiz(quizID));
			
			RequestDispatcher dpatch = request.getRequestDispatcher("add-questions.jsp");
			dpatch.forward(request, response);
			return;
		}
		
		RequestDispatcher dpatch = request.getRequestDispatcher("create-question.jsp");
		dpatch.forward(request, response);	
	}

}
